package com.hitqz.robot.netty.encoder;

import com.hitqz.robot.netty.message.ChipMessage;
import com.hitqz.robot.util.ChipToolKit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author xupkun
 * @date 2023/8/14
 */
@Slf4j
public class HitChipEncoder extends MessageToByteEncoder<ChipMessage> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ChipMessage message, ByteBuf byteBuf) throws Exception {

        byteBuf.writeBytes(ChipMessage.head);

        byteBuf.writeByte(message.getLength());
        // 注意这边之前已经处理成小端模式
        byteBuf.writeBytes(message.getData());

        byteBuf.writeByte(message.getCheckSum());

        if (log.isDebugEnabled()) {
            byte[] fullMessage = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, fullMessage);
            String hexMessage = ChipToolKit.bytesToHexString(fullMessage);
            // 获取远程地址（IP和端口）
            InetSocketAddress remoteAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
            String ip = remoteAddress.getAddress().getHostAddress();
            int port = remoteAddress.getPort();
            log.debug("[track] send to [{}:{}]: {} ",ip,port,hexMessage);
        }

    }


}
